<?php
/**
 * [ActiveRecord] 模型查询类,构造出操作SQL
 *
 * @version $Id: Command.php 113 2013-09-14 03:02:33Z linsir123 $
 * @package ActiveRecord
 */
class ARCommand extends SqlBase
{
	/**
	 * 数据表替换
	 */
	const AS_TABLE = '`a`';

	/**
	 * `数据库表名`
	 *
	 * @var string
	 */
	public $table;

	/**
	 * 数据操作或查询使用的条件对象
	 *
	 * @var ARCondition
	 */
	public $oCondition;

	/**
	 * 构造函数
	 *
	 * @param string $table 需要查询的数据库表名
	 * @param ARCondition $oCondition 查询条件对象
	 */
	public function __construct($table, & $oCondition)
	{
		///
		$this->setTable($table);

		///
		$this->oCondition = $oCondition;
	}

	/**
	 * Insert
	 *
	 * @param array $data 待插入的数据
	 *
	 * @return string
	 */
	public function insert($data)
	{
		///
		$format = "INSERT INTO %s (%s) VALUES (%s)";
		$data = $this->_escape($data);
		$fields = array_keys($data);

		///
		$fields = $this->_quote($fields);
		$query = sprintf($format,
			$this->table,
			implode(',', $fields),
			implode(',', $data));

		///
		return $this->_joinQuery($query, false);
	}

	/**
	 * Insert On Duplicate
	 *
	 * @param array $data 待插入的数据
	 * @param array $duplicateData 需要执行更新的数据
	 *
	 * @return string
	 */
	public function insertDuplicate($data, $duplicateData)
	{
		///
		$query = $this->insert($data);

		///
		$format = " ON DUPLICATE KEY UPDATE %s";
		$data = $this->_escape($duplicateData);
		$fields = array_keys($data);

		$bits = array();
		foreach ($fields as $f)
			$bits[] = $this->_quote($f) . '=' . $data[$f];

		$query .= sprintf($format, implode(',', $bits));

		///
		return $query;
	}

	/**
	 * Delete
	 *
	 * @return string
	 */
	public function delete()
	{
		///
		$format = "DELETE %s FROM %s AS %s";
		$query = sprintf($format,
			self::AS_TABLE,
			$this->table,
			self::AS_TABLE);

		///
		return $this->_joinQuery($query);
	}

	/**
	 * Update
	 *
	 * @param array $data 待更新的数据
	 *
	 * @return string
	 */
	public function update($data)
	{
		///
		$format = "UPDATE %s AS %s SET %s";
		$data = $this->_escape($data);
		$fields = array_keys($data);

		///
		$bits = array();
		foreach ($fields as $f)
			$bits[] = $this->_quote($f) . '=' . $data[$f];

		$query = sprintf($format,
			$this->table,
			self::AS_TABLE,
			implode(',', $bits));

		///
		return $this->_joinQuery($query);
	}

	/**
	 * 重新设置操作的数据表名
	 *
	 * @param string $table 需要查询的数据库表名
	 */
	public function setTable($table)
	{
		$this->table = $this->_quote($table);
	}

	/**
	 * 操作数据表,执行操作后清空WHERE条件
	 *
	 * @param $query
	 * @param bool $useCondition
	 *
	 * @return string
	 */
	private function _joinQuery($query, $useCondition = true)
	{
		if (! empty($useCondition))
			$query .= $this->oCondition->__toString();

		///
		$this->oCondition->clean();

		///
		return $query;
	}
}
